﻿using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Domain.GlobalClass;
using Zocono.WCS.Domain.JobExcutorDomain;

namespace Zocono.WCS.HangfireHost.Hubs
{
    public class EquipmentSignalRService : Hub
    {
        private readonly IJobExcutorService _jobExcutorService;
        private readonly IReadDbJobService _readDbJobService;
        private readonly ILogUtil _logUtil;

        public IConfiguration Configuration { get; }

        //监控作业配置
        public Dictionary<string, EquipmentState> EquipmentStates;


        public EquipmentSignalRService(IJobExcutorService iJobExcutorService, IReadDbJobService iReadDbJobService, IConfiguration configuration, ILogUtil logUtil)
        {
            _jobExcutorService = iJobExcutorService;
            _readDbJobService = iReadDbJobService;
            Configuration = configuration;
            _logUtil = logUtil;
            EquipmentStates = new Dictionary<string, EquipmentState>();
            //封装需要获取状态的程序和工序
            var equipmentStates = Configuration.GetSection("EquipmentState").Get<List<EquipmentState>>();
            foreach (var equipmentState in equipmentStates)
            {
                EquipmentStates.Add(equipmentState.ProgrameName, equipmentState);
            }
        }

        /// <summary>
        /// 获取监控数据
        /// </summary>
        /// <param name="name"></param>
        /// <param name="proName"></param>
        /// <param name="hubName"></param>
        /// <returns></returns>
        private async Task GetMonitorData(string name, string proName, string hubName)
        {
            try
            {
                var equipmentState = EquipmentStates[proName];
                foreach (var item in equipmentState.Jobs)
                {
                    string key = $"{proName}_{item}";
                    //从内存中拿数据
                    if (GlobalResource.ProcessModuleDicts.TryGetValue($"{key}", out var proDict))
                    {
                        await Clients.Client(name).SendAsync(hubName, JsonConvert.SerializeObject(proDict));
                    }
                    else
                    {
                        _logUtil.Error($"内存中不存在【{key}】-PLC读取监控数据");
                    }
                    await Task.Delay(2);
                }
            }
            catch (Exception ex)
            {
                _logUtil.Error($"获取监控数据异常,{proName},{hubName}：{ex}");
            }
           
        }


        /// <summary>
        /// 一楼监控数据发送到客户端
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task SendFloor1ToClient(string name)
        {
            await GetMonitorData(name, "Pro_SentPackingD", "Floor1CallByHub");
        }

        /// <summary>
        /// 二楼监控数据发送到客户端
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task SendFloor2ToClient(string name)
        {
            await GetMonitorData(name, "Pro_SC2001", "Floor2CallByHub");
        }

        /// <summary>
        /// 三楼监控数据发送到客户端
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task SendFloor3ToClient(string name)
        {
            await GetMonitorData(name, "Pro_SC3001", "Floor3CallByHub");
        }

        /// <summary>
        /// 四楼监控数据发送到客户端
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task SendFloor4ToClient(string name)
        {
            await GetMonitorData(name, "Pro_SC4001", "Floor4CallByHub");
        }

        /// <summary>
        /// 五楼监控数据发送到客户端
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task SendFloor5ToClient(string name)
        {
            await GetMonitorData(name, "Pro_StateTop", "Floor5CallByHub");
        }



        ////客户端被调用
        public void CallByClient(string msg)
        {
            Console.WriteLine("=============客户端被调用开始=============");
            Console.WriteLine("客户端发来消息CallByClient" + msg);
            Console.WriteLine("=============客户端被调用结束=============");
        }

        #region 测试代码

        //public async Task ConnectAsync(string name)
        //{
        //    await Clients.AllExcept(Context.ConnectionId).SendAsync("online", $"{name}进入了群聊");
        //}

        //public async Task SignOutAsync(string name)
        //{
        //    await Clients.AllExcept(Context.ConnectionId).SendAsync("online", $"{name}离开了群聊");
        //}

        //public async Task SendMessageAsync(string user, string message)
        //{
        //    // Call the broadcastMessage method to update clients.
        //    await Clients.All.SendAsync("SendMessages", user, message);
        //}
        //public async Task ReceiveMessageAsync(string user, string message)
        //{
        //    // Call the broadcastMessage method to update clients.
        //    await Clients.All.SendAsync("ReceiveMessages", user, message);
        //}
        ////客户端被调用
        //public void CallByClient(string msg)
        //{
        //    Console.WriteLine("=============客户端被调用开始=============");
        //    Console.WriteLine("客户端发来消息CallByClient" + msg);
        //    Console.WriteLine("=============客户端被调用结束=============");
        //}
        ////客户端被调用（有返回值）
        //public string CallByClientWithReturnValue(string msg)
        //{
        //    Console.WriteLine("=============客户端被调用（有返回值）开始=============");
        //    Console.WriteLine("客户端发来消息CallByClientWithReturnValue" + msg);
        //    Console.WriteLine("=============客户端被调用（有返回值）结束=============");
        //    return MethodInfo.GetCurrentMethod()?.Name + "    ";
        //}
        ////调用客户端方法
        //public string CallClient(string msg)
        //{
        //    Console.WriteLine("=============调用客户端方法开始=============");
        //    Console.WriteLine($"客户端传来数据：{msg}");
        //    Clients.Caller.SendAsync("CallByHub", $"CallClient    by {Context.ConnectionId}");
        //    Console.WriteLine("=============调用客户端方法结束=============");
        //    return MethodInfo.GetCurrentMethod()?.Name + "    ";
        //}
        ////全员发送方法
        //public string CallAllClient(string msg)
        //{
        //    Console.WriteLine("=============全员发送方法开始=============");
        //    Console.WriteLine($"客户端传来数据：{msg + Context.ConnectionId}");
        //    Clients.All.SendAsync("CallByHub", $"CallAllClient    by {Context.ConnectionId}");
        //    Console.WriteLine("=============全员发送方法结束=============");
        //    return MethodInfo.GetCurrentMethod()?.Name + "    ";
        //}
        ////自身以外发送方法
        //public string CallOtherClient(string msg)
        //{
        //    Console.WriteLine("=============全员发送方法开始=============");
        //    Console.WriteLine($"客户端传来数据：{msg}");
        //    Clients.Others.SendAsync("CallByHub", $"CallOtherClient    by {Context.ConnectionId}");
        //    Console.WriteLine("=============全员发送方法结束=============");
        //    return MethodInfo.GetCurrentMethod()?.Name + "    ";
        //}
        ////分组发送
        //public void RegesterToGroup(string grpName)
        //{
        //    Groups.AddToGroupAsync(Context.ConnectionId, grpName);
        //}

        //public void SendToGroup(string name)
        //{
        //    Console.WriteLine("=============分组发送开始=============");
        //    Console.WriteLine($"客户端传来数据：{name}");
        //    Clients.Group(name).SendAsync("CallByHub", $"SendToGroup    by {Context.ConnectionId}");
        //    Console.WriteLine("=============分组发送结束=============");
        //}

        ////指定发送
        //public void SendToClient(string name)
        //{

        //    Console.WriteLine("=============指定发送开始=============");
        //    Clients.Client(name).SendAsync("CallByHub", $"SendToClient    by {Context.ConnectionId}");
        //    Console.WriteLine("=============指定发送结束=============");
        //}

        #endregion

    }
}
